<template>
    <base-breadcrumb :title="$route.meta.title">
        <title-name title="双优化推优审批"></title-name>
        <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
            <a-spin :spinning="loading">
                <a-card :bordered="false">
                    <title-name title="节点信息"></title-name>
                    <custom-form :form="form" :formList="formListNode" editModel="0"> </custom-form>
                </a-card>

                <!--推优审批-项目经理及之后节点-->
                <a-card v-if="taskDefKey!=='XMB_ZGCS_AUDIT'">
                    <title-name title="审批意见"></title-name>
                    <custom-form :form="form" :formList="formList2" editModel="0"> </custom-form>
                </a-card>

                <a-card>
                    <title-name title="补充双优化案例信息"></title-name>
                    <custom-form :form="form" :formList="formList" editModel="0"> </custom-form>
                </a-card>




                <a-card :bordered="false">
                    <Consultation
                            :proc-inst-id="procInstId"
                            :is-show-btn="!$route.query.isView&&($route.query.isMonitoring ? ($route.query.monitoringType==='process' ? true: false): true)"
                            :task-name="taskName"
                            :sub-approver-list.sync="subApproverList"
                    >
                        <template slot="approverButton">
                            <a-button type="primary" :loading="loading.PASS" @click="handleSave('PASS')">审批通过</a-button>
                            <a-button type="primary" class="ml12" :loading="loading.REJECT" @click="handleSave('REJECT')">审批不通过</a-button>
                        </template>
                    </Consultation>
                </a-card>
                <a-card>
                    <template>
                        <title-name title="审批流程信息" />
                        <div class="btns-wrapp mb20">
                            <a-button type="primary" @click="visibleState.auditProcess = true"> 审批流程图 </a-button>
                        </div>
                        <a-spin tip="流程信息加载中..." :spinning="flowRequesting" />
                        <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
                            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                            <template slot="opinions" slot-scope="text">
                                <a-tooltip placement="topLeft">
                                    <template slot="title">
                                        <span> {{ text }}</span>
                                    </template>
                                    <span> {{ text }}</span>
                                </a-tooltip>
                            </template>
                        </a-table>
                    </template>
                </a-card>
                <!-- 页脚操作栏 -->
                <div class="btn_box page-btn-right-top" style="top: 0">
                    <a-button  @click="handleActiveClose">关闭</a-button>
                </div>
                <ApprovalDetails
                        :title="'审批流程信息'"
                        :business-id="id+'_P_R_O'"
                        :visible="visibleState.auditProcess"
                        @cancel="visibleState.auditProcess = false"
                        @confirm="visibleState.auditProcess = false"
                />
            </a-spin>
        </a-form-model>
        <addImplement @finish="finish"></addImplement>
    </base-breadcrumb>
</template>

<script>
  import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
  import ApprovalDetails from '@/components/approvalDetails'
  import { columnApprove, column, dataSource, dataSource2,dataSource3, dataSource4 } from './model.js'

  import { messageRead } from '@/api/messageSend'
  import { getOrgEmployeesListBy } from '@/api/commons'
  import { getProcessNodeList, completeTask } from '@/api/process'
  import moment from 'moment'
  import Vue from 'vue'
  import Consultation from '@/views/matters/approval/components/consultation'
  import {updatePromotion} from "@/api/project/implementation"
  import addImplement from "./addImplement"
  export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
      ApprovalDetails,
      Consultation,
      addImplement
    },
    data() {
      return {
        column,
        columnApprove,
        dataSource,
        dataSource2,
        dataSource3,
        dataSource4,
        visibleState: {
          auditProcess: false
        },
        loading: false, // 加载控件
        visible: false, //弹窗控件
        editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
        form: {
          fileInfoList: [],
          technicalReviewYearlyPlans: [],
          projectDeptId: '',
          sendPersonName: '',
          receiveUnitName: '',
          sendUnitName: '',
          receivePersonName: '',
          opinions: '',
          cc: [],
          currentTime: '',
          time: ''
        }, // 表单
        id: '',
        yearsOpen: false,
        projectName: '',
        loadingBtn: {
          PASS: false,
          REJECT: false,
          DELETE: false,
          DRAFT: false,
          SUBMITTED: false,
          REJECTED: false
        },
        detailId: '',
        rules: {
          messageType: [{ required: true, message: '请选择' }],
          messageName: [{ required: true, message: '请输入' }],
          messageNumber: [{ required: true, message: '请输入' }],
          dataType: [{ required: true, message: '请选择' }],
          messageAbstract: [{ required: true, message: '请输入' }],
          sendUnitName: [{ required: true, message: '请输入' }],
          sendPersonName: [{ required: true, message: '请输入' }],
          receiveUnitName: [{ required: true, message: '请输入' }],
          receivePersonName: [{ required: true, message: '请输入' }],
          receiveTime: [{ required: true, message: '请选择' }],
          remarks: [{ required: true, message: '请输入' }],
          // opinions: [{ required: true, message: '请输入' }],
          cc: [{ required: true, message: '请选择' ,type: "array"}],
          useSite: [{ required: true, message: '请输入' }],
          optimizationBackground: [{ required: true, message: '请输入' }],
          optimizationRationale: [{ required: true, message: '请输入' }],
          applicationScope: [{ required: true, message: '请输入' }],
          usingTips: [{ required: true, message: '请输入' }],
        },
        typess: '',
        init: false, // 初始化控件
        titles: ['日常资料管理查看', '日常资料管理编辑', '日常资料管理新增'],
        //审批相关
        approveInfos: [], // 审批流程信息
        procInstId: '', //当前流程实例ID
        taskId: '', //当前流程节点ID
        processName: '', //流程名称
        taskName: '', //当前流程节点名称
        taskDefKey: '', //任务标识
        currentTime: '', //当前审批时间
        currentUser: '', //当前审批人
        flowRequesting: false,
        detailUrl: null, //详情地址

        assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
        assignCode: '', //候选组编码 岗位编码
        assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
        businessType: '', //业务类型 0 项目
        // 下级审批人
        subApproverList: [],
        isDiabled: false
      }
    },
    props: {
      isAudit: {
        // 是否作为审批详情
        type: Boolean,
        default: false
      }
    },
    watch: {
      isAudit: {
        immediate: true,
        handler(val) {
          if (val) {
            this.$nextTick(() => {
              this.editModel = 0
            })
          }
        }
      },
      'form.messageType'(e) {
        if (this.editModel != 0 && this.init) {
          this.$nextTick(() => {
            if (this.form.messageType == 0) {
              this.form.sendUnitName = this.form.projectName
              this.form.receiveUnitName = ''
            } else {
              this.form.receiveUnitName = this.form.projectName
              this.form.sendUnitName = ''
            }
            this.form.receivePersonName = ''
            this.form.sendPersonName = ''
          })
        }
      }
    },
    mounted() {
        if(this.$route.query.isView) {
            this.isDiabled = true
        }
      this.formattingData() //格式化审批流数据
      this.readMessage()
    },
    computed: {
      formList() {
        let that = this
        return [
          {
            keyName: 'classificationName',
            type: 'BaseInput',
            disabled: true,
            label: '详细分类'
          },
          {
            keyName: 'part',
            type: 'BaseInput',
            disabled: true,
            label: '分部'
          },
          {
            keyName: 'useSite',
            type: 'BaseInput',
            label: '使用部位',
              attrs: {
              maxLength: 3000
            },
            disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled,
            span: 24
          },
          {
            keyName: 'optimizationBackground',
            type: 'BaseTextarea',
            label: '优化背景',
            attrs: {
              maxLength: 5000
            },
            disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled,
            placeholder: '请输入。示例：本工程11-15轴/A-G轴东侧基坑临近地铁4号线地铁隧道，该部位基坑防护采用支护桩形式，结构外墙距支护桩约800mm宽，支护桩壁上设有钢梁，局部小于800mm。原设计回填土为为素土及2:8灰土，夯实作业-蛙式打夯机无法工作，回填质量无法得到保障。',
            span: 24
          },
          {
            keyName: 'optimizationRationale',
            type: 'BaseTextarea',
            label: '优化理由',
            attrs: {
              maxLength: 5000
            },
            disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled,
            span: 24
          },
          {
            keyName: 'applicationScope',
            type: 'BaseTextarea',
            label: '适用范围',
            attrs: {
              maxLength: 3000
            },
            disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled,
            placeholder: '请输入。示例：适用于预应力锚索+排桩支护形式，且工期紧、模板亏损的项目。',
            span: 24
          },
          {
            keyName: 'usingTips',
            type: 'BaseTextarea',
            label: '使用提示',
            attrs: {
              maxLength: 3000
            },
            disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled,
            placeholder: '请输入。示例：施工过程应注意控制网喷厚度满足优化要求，施工完成后不能满足抵抗雨季的预计效果，同时还会影响监理、过控、业主等单位对工程量的确认。',
            span: 24
          },
          {
            keyName: 'fileInfoList',
            type: 'uploadFile',
            label: '现场实施照片（请至少保留一张照片）',
            span: 24,
           disabled: that.taskDefKey!=='XMB_ZGCS_AUDIT' ||  that.isDiabled,
            attrs: {
              serviceDel: false,
              isUploadImgAndVideoLog: that.taskDefKey==='XMB_ZGCS_AUDIT'&& !that.isDiabled,
              isUploadImgAndVideo: true,
              showUploadList: false,
              editModel: (that.taskDefKey!=='XMB_ZGCS_AUDIT' || that.isDiabled) ? 0 : 1,
              uploadType: 'image',
              delFile: 1,
              showUploadBtn: false
            },
            businessCode: 'BIM06'
          },
        ]
      },
      formList2() {
        return [
          {
            keyName: 'opinions',
            type: 'BaseTextarea',
            span: 24,
            label: '审批意见'
          }
        ]
      },
      formListNode() {
        return [
          {
            keyName: 'taskName',
            type: 'BaseInput',
            label: '当前节点名称',
            disabled: true,
            span: 8
          },
          {
            keyName: 'currentUser',
            type: 'BaseInput',
            label: '审批人',
            disabled: true,

            span: 8
          },
          {
            keyName: 'time',
            type: 'BaseInput',
            label: '审批时间',
            disabled: true,

            span: 8
          }
        ]
      }
    },
    methods: {
      finish(val) {
        this.$set(this.form, 'part', val.part)
        this.$set(this.form, 'classificationName', val.classificationName)
        this.$set(this.form, 'applicationScope', val.applicationScope)
        this.$set(this.form, 'optimizationBackground', val.optimizationBackground)
        this.$set(this.form, 'useSite', val.useSite)
        this.$set(this.form, 'usingTips', val.usingTips)
        this.$set(this.form, 'fileInfoList', val.promotionFileIdsInfo || [])
        if(val.optimizationRationale) {
          this.$set(this.form, 'optimizationRationale', val.optimizationRationale)
        } else {
          let str =  val?.contentDels.replace(/<[^<]+?>/g, '')
          this.$set(this.form, 'optimizationRationale', str)
        }
      },
      readMessage() {
        if (!this.detailId) return
        const params = {
          ids: [this.detailId]
        }
        messageRead(params).then(res => {
          if (res && res.data && res.data.code == '200') {
            this.$message.success('查看成功！')
            let count = Number(this.$store.getters['messageInfo/GET_TOREADCOUNT'] - 1)
            this.$store.commit('messageInfo/SET_TOREADCOUNT', count > 0 ? count : 0)
          } else {
            this.$message.error(res.data.message ? res.data.message : '查看失败！')
          }
        })
      },
      formattingData() {
        try {
          setTimeout(() => {
            const requireDom = document.querySelectorAll('.ant-form-item-required')
            requireDom.forEach(item => {
              item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
            })
          }, 0)
        } catch {}
        this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
        this.id = this.$route.query.id
        const {
          type,
          code,
          level,
          btype,
          businessId,
          procInstId,
          name,
          processName,
          detailUrl,
          taskId,
          taskDefKey,
          durationInMillis
        } = this.$route.query
        if (type) {
          this.assignType = type
          this.assignCode = code
          this.assignLevel = level
          this.businessType = btype
        }
        this.id = businessId.replace("_P_R_O", '')
        this.detailId = this.$route.query.detailId
        this.typess = this.$route.query.typess
        // this.taskDefKey = 'GS_CWZJBJL_AUDIT'
        if (!this.id) {
          this.$error({ content: '无指定业务ID，将自动关闭' })
          setTimeout(() => {
            window.close()
          }, 1500)
          return
        }
        this.procInstId = procInstId
        this.form.currentUser = Vue.getAcloudProvider().getUserInfo().name
        this.form.taskName = decodeURIComponent(name)
        this.taskName =   this.form.taskName
        this.form.durationInMillis = durationInMillis
        this.processName = decodeURIComponent(processName)
        document.title = this.processName + '-' + this.taskName
        if (detailUrl) {
          this.detailUrl = decodeURIComponent(detailUrl)
        }
        this.taskId = taskId
        this.taskDefKey = taskDefKey

        this.form.time = moment(new Date()).format('YYYY-MM-DD HH:mm')
        this.currentTime = this.form.currentTime
        this.getProcessNodes()
      },
      //流程节点信息
      getProcessNodes() {
        this.flowRequesting = true
        getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
          .then(res => {
            if (res.code === 200) {
              const data = res.data
              const userIds = data.map(d => {
                if (d.formData) {
                  d.formData = JSON.parse(d.formData)
                }
                return d.assignee
              })
              getOrgEmployeesListBy({ userIds, delete: true }).then(employees => {
                this.flowRequesting = false
                res.data.forEach(r => {
                  employees.data.some(e => {
                    if (e.userId === r.assignee) {
                      r.userName = e.name
                      return true
                    }
                  })
                })

                this.approveInfos = res.data
              })
            }
          })
          .catch(() => {
            this.flowRequesting = false
          })
      },
      // 处理增、删、改操作
      handleSave(status) {
        if (this.loadingBtn[status]) return
        if (status == 'PASS') {
          if (this.validateForm()) {
            this.handelApproval(status)
          }
        } else {
          if (this.validateForm()) {
            this.handelUnApproval(status)
          }
        }
      },
      /**
       * 提交表单
       */
      validateForm() {
        let flag = false
        this.$refs.ruleForm.validate(e => {
          if (e) {
            flag = true
          }
        })

        return flag
      },
      handelApproval(staus) {
        // 审批通过
        const _this = this
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批通过？',
          okType: 'danger',
          onOk() {
            return new Promise((resolve, reject) => {
              _this
                .submit(false, _this.createApproverList(_this.subApproverList))
                .then(() => {

                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch((err) => {
              console.log(err)
              this.$error({ content: '审批提交失败，请稍后重试' })
            })
          },
          onCancel() {}
        })
      },
      notifyParent() {
        window.opener.postMessage('finish', window.location.origin)
      },
      handelUnApproval(staus) {
        // 审批不通过
        const _this = this
        const confirmWin = this.$confirm({
          title: '警告提醒！',
          content: '确定审批不通过？',
          okType: 'danger',
          onOk() {
            return new Promise((resolve, reject) => {
              _this
                .submit(true)
                .then(() => {
                  resolve()
                  confirmWin.destroy()
                })
                .catch(() => reject)
            }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
          },
          onCancel() {}
        })
      },
      handleClose() {
        this.$multiTab.close()
      },
      /**
       * @description: 组装下级审批人数据
       * @param {array} subApproverList 下级审批人表格数据
       * @return {object} 下级审批人数据
       */
      createApproverList(subApproverList) {
        const subordinateApproverList = {}
        subApproverList.forEach((item) => {
          if (item?.approver && item.approver.length > 0) {
            subordinateApproverList[item.taskInfo.id] = {
              assgins: item.approver?.map((el) => el.key).join(','),
              assignTypeEnum: 2
            }
          }
        })
        return subordinateApproverList
      },
      async submit(reject, users) {

        delete this.form.auditStatus
          let options = this.form.opinions ?  this.form.opinions  : (reject ?'不同意': '同意')
        const data = {
          formData: {
            opinions: options,
            content: '双优化实施销项',
            title: '双优化实施销项',
            reject
          },
          variables: {
            ...users,
            reject
          },
          procInstId: this.procInstId,
          taskId: this.taskId,
          userId: Vue.getAcloudProvider().getUserInfo().id
        }
        return completeTask(data)
          .then( async res => {
            if (res.status === 200) {
                let fileIds = []
                this.form.fileInfoList.forEach(item=>{
                  fileIds.push(item.commonId)
                })
                let data = {
                  applyId: this.id,
                  fileIds,
                  ...this.form
                }
                await updatePromotion(data)
              this.notifyParent() // 通知父窗口
              // this.$success({
              //   content: '审批提交成功，即将自动关闭当前窗口',
              //   onOk() {
                  window.close()
              //   }
              // })
              // setTimeout(() => {
              //   window.close()
              // }, 2000)
            } else {
              this.$error({ content: '审批提交失败，请稍后重试' })
            }
            return res
          })
          .catch(err => {
            return err
          })
      },
      /**
       * @description: 所属单位获取项目信息设置组织id
       * @param {object} info 项目信息
       * @return {void}
       */
      getProjectInfo(info){
        this.form.projectDeptId = info?.projectDeptOrgId
      }
    }
  }
</script>
<style lang="less" scoped>
    /deep/ .form-item  {
        .ant-input:not([disabled]),
        .ant-select:not(.ant-select-disabled) .ant-select-selection,
        .ant-calendar-picker-input,
        .ant-input-number:not([disabled]),
        .ant-cascader-picker {
            border-color: #e4ac0b;
            background-color: #fff9e8;
        }
        .remark {
            .ant-input {
                border-color: inherit;
                background-color: initial;
            }
        }
    }
    .item {
        margin-left: 60px;
        margin-bottom: 0;
    }
    .item .ant-form-item {
        margin-top: -28px;
    }
</style>
